package com.example.anpnovel.controller.crud;


import com.example.anpapi.entity.po.novelmodel.Chapter.Chapter;
import com.example.anpapi.entity.vo.R;
import com.example.anpnovel.service.interfaces.ChapterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/chapter")
public class ChapterController {

    @Autowired
    private ChapterService chapterService;

    /**
     * 章节添加
     * @param chapter
     * @return
     */
    @PostMapping("/save")
    public R<Chapter> save(@RequestBody Chapter chapter){
        log.info("章节添加:{}", chapter);
        chapterService.save(chapter);
        return R.success(chapter,"章节添加成功");
    }

    /**
     * 根据章节id删除章节
     * @param chapter
     * @return
     */
    @DeleteMapping("/remove")
    public R<String> remove(@RequestBody Chapter chapter){
        log.info("章节删除:{}", chapter);
        if(chapterService.getById(chapter.getId()) != null)
        {
            chapterService.removeById(chapter.getId());
            return R.success(null,"章节删除成功");
        }
        return R.error("未找到该章节");
    }

    /**
     * 根据章节id查找章节
     * @param id
     * @return
     */
    @GetMapping("/get")
    public R<Chapter> get(@RequestParam(value = "id") Long id) {
        log.info("查询章节的id为{}", id);
        Chapter chapter = chapterService.getById(id);
        return R.success(chapter, "查询章节成功");
    }

    /**
     * 根据作品id查找所有章节
     * @param novelId
     * @return
     */
    @GetMapping("/getByNovelId")
    public R<List<Chapter>> getByNovelId(@RequestParam(value = "novelId") Long novelId) {
        log.info("查询作品id为{}的所有章节", novelId);
        List<Chapter> chapters = chapterService.lambdaQuery()
                .eq(Chapter::getNovelId, novelId)
                .orderByAsc(Chapter::getSortOrder)
                .list();
        return R.success(chapters, "查询章节成功");
    }

    /**
     * 根据卷id查找所有章节
     * @param volumeId
     * @return
     */
    @GetMapping("/getByVolumeId")
    public R<List<Chapter>> getByVolumeId(@RequestParam(value = "volumeId") Long volumeId) {
        log.info("查询卷id为{}的所有章节", volumeId);
        List<Chapter> chapters = chapterService.lambdaQuery()
                .eq(Chapter::getVolumeId, volumeId)
                .orderByAsc(Chapter::getSortOrder)
                .list();
        return R.success(chapters, "查询章节成功");
    }

    /**
     * 修改章节
     * @param chapter
     * @return
     */
    @PostMapping("/update")
    public R<Chapter> update(@RequestBody Chapter chapter){
        log.info("修改的章节为{}", chapter);
        chapterService.updateById(chapter);
        return R.success(chapter,"修改章节成功");
    }

}

